package com.ymt.bpm.web;

import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ymt.bpm.util.Const;
import com.ymt.bpm.util.JwtUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by Johnny on 2017/11/26.
 */
public class MJwtFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // do nothing
    }

    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        if (checkAuthHeader(req)) {
            filterChain.doFilter(request, response);
        } else {
            response.setCharacterEncoding(Const.ENCODING);
            response.setContentType("application/json; charset=utf-8");
            response.getWriter().write("{\"loginRequired\":true}");
        }
    }

    @Override
    public void destroy() {
        // do nothing
    }

    private boolean checkAuthHeader(HttpServletRequest req) {
        String jwtToken = req.getHeader("Authorization");
        if (jwtToken==null || !jwtToken.startsWith("JWT ")) {
            return false;
        }
        jwtToken = jwtToken.substring(4);
        DecodedJWT jwt = JwtUtil.decode(jwtToken);
        if (jwt==null) {
            return false;
        } else {
            String loginName = jwt.getSubject();
            req.setAttribute(Const.JWT_USER, loginName);
            req.setAttribute(Const.DISPLAYNAME, jwt.getClaim(Const.DISPLAYNAME).asString());
            Claim tenantIdClaim = jwt.getClaim(Const.TENANT_ID);
            if (tenantIdClaim!=null) {
                req.setAttribute(Const.TENANT_ID, tenantIdClaim.asString());
            }
        }
        return true;
    }
}
